<?php

/*
  Copyright (c) 2005 Kreditor AB

  Released under the GNU General Public License
*/

// INCLUDE THE LANGUAGE SUPPORT FILE
if(strpos($_SERVER['SCRIPT_FILENAME'],'admin'))
    @include_once '../'.DIR_WS_CLASSES . 'kreditor_lang.php';
else
    @include_once DIR_WS_CLASSES . 'kreditor_lang.php';

class prekreditor_nor
{
    var $code, $title, $description, $enabled;

	// class constructor
    function prekreditor_nor()
    {

		global $order;

		$this->code = 'prekreditor_nor';
		$this->title = MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_TITLE;
		$this->description = MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_DESCRIPTION;
		$this->enabled = ((MODULE_PAYMENT_PREKREDITOR_NOR_STATUS == 'True') ? true : false);

		if(isset($order))
		{
			$currency = $order->info['currency'];
			if ($currency != "NO" && $currency != "no" && $currency != "NOK" && $currency != "nok")
				$this->enabled = false;
		}

		$this->sort_order = MODULE_PAYMENT_PREKREDITOR_NOR_SORT_ORDER;

		if ((int)MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_STATUS_ID > 0)
			$this->order_status = MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_STATUS_ID;

		if (is_object($order))
	    	$this->update_status();

    }

// class methods
    function update_status() {
	global $order, $db;

	if ($this->enabled == true && (int)MODULE_PAYMENT_PREKREDITOR_NOR_ZONE > 0) {
	    $check_flag = false;
	    $check = $db->Execute("select zone_id from " .
					TABLE_ZONES_TO_GEO_ZONES .
					" where geo_zone_id = '" .
					MODULE_PAYMENT_PREKREDITOR_NOR_ZONE .
					"' and zone_country_id = '" .
					$order->billing['country']['id'] .
					"' order by zone_id");

	    // found and fixed by Payam Karimian
	    while (!$check->EOF) {
		if ($check->fields['zone_id'] < 1) {
		    $check_flag = true;
		    break;
		} elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
		    $check_flag = true;
		    break;
		}
		$check->MoveNext();
	    }

	    if ($check_flag == false) {
		$this->enabled = false;
	    }
	}
    }

    function javascript_validation() {
	return false;
    }

    function selection() {
	global $order, $db;

	$has_dob = false;

	return array('id' => $this->code,
		'module' => $this->title,
		'fields' => array(
			array('title' => KREDITOR_LANG_INFO_SE_IMGCONSUMERCREDIT,
					'field' => ""),
			array('title' => KREDITOR_LANG_INFO_NO_FIRSTNAME,
				'field' => zen_draw_input_field('prekreditor_nor_fname',
					$order->billing['firstname'])),
			array('title' => KREDITOR_LANG_INFO_NO_LASTNAME,
				'field' => zen_draw_input_field('prekreditor_nor_lname',
					$order->billing['lastname'])),
			array('title' => KREDITOR_LANG_INFO_NO_STREETADDRESS,
			    'field' => zen_draw_input_field('prekreditor_nor_street',
					$order->billing['street_address'])),
			array('title' => KREDITOR_LANG_INFO_NO_POSTCODE,
			    'field' => zen_draw_input_field('prekreditor_nor_postno',
					$order->billing['postcode'])),
			array('title' => KREDITOR_LANG_INFO_NO_CITY,
			    'field' => zen_draw_input_field('prekreditor_nor_city',
					$order->billing['city'])),
			array('title' => KREDITOR_LANG_INFO_NO_PHONENUMBER,
			    'field' => zen_draw_input_field('prekreditor_nor_phone',
					$order->customer['telephone'])),
			array('title' => KREDITOR_LANG_INFO_NO_EMAIL,
			    'field' => zen_draw_input_field('prekreditor_nor_email',
					$order->customer['email_address']))));
    }

    function pre_confirmation_check() {
	global $order;

	$this->prekreditor_nor_fname = $_POST['prekreditor_nor_fname'];
	$order->delivery['firstname'] = $this->prekreditor_nor_fname;
	$order->billing['firstname'] = $this->prekreditor_nor_fname;

	$this->prekreditor_nor_lname = $_POST['prekreditor_nor_lname'];
	$order->delivery['lastname'] = $this->prekreditor_nor_lname;
	$order->billing['lastname'] = $this->prekreditor_nor_lname;

	$this->prekreditor_nor_street = $_POST['prekreditor_nor_street'];
	$order->delivery['street_address'] = $this->prekreditor_nor_street;
	$order->billing['street_address'] = $this->prekreditor_nor_street;

	$this->prekreditor_nor_postno = $_POST['prekreditor_nor_postno'];
	$order->delivery['postcode'] = $this->prekreditor_nor_postno;
	$order->billing['postcode'] = $this->prekreditor_nor_postno;

	$this->prekreditor_nor_city = $_POST['prekreditor_nor_city'];
	$order->delivery['city'] = $this->prekreditor_nor_city;
	$order->billing['city'] = $this->prekreditor_nor_city;

	$this->prekreditor_nor_phone = $_POST['prekreditor_nor_phone'];
	$order->delivery['telephone'] = $this->prekreditor_nor_phone;
	$order->billing['telephone'] = $this->prekreditor_nor_phone;

	$this->prekreditor_nor_email = $_POST['prekreditor_nor_email'];
	$order->delivery['email_address'] = $this->prekreditor_nor_email;
	$order->billing['email_address'] = $this->prekreditor_nor_email;
    }

    function confirmation() {
	return false;
    }

    function process_button() {
	global $HTTP_SERVER_VARS, $order, $order_total_modules, $prekreditor_nor_ot;

	$process_button_string =
	    zen_draw_hidden_field('prekreditor_nor_fname',  $this->prekreditor_nor_fname) .
	    zen_draw_hidden_field('prekreditor_nor_lname',  $this->prekreditor_nor_lname) .
	    zen_draw_hidden_field('prekreditor_nor_street', $this->prekreditor_nor_street) .
	    zen_draw_hidden_field('prekreditor_nor_postno', $this->prekreditor_nor_postno) .
	    zen_draw_hidden_field('prekreditor_nor_city',   $this->prekreditor_nor_city) .
	    zen_draw_hidden_field('prekreditor_nor_phone',  $this->prekreditor_nor_phone) .
	    zen_draw_hidden_field('prekreditor_nor_email',  $this->prekreditor_nor_email);
	

	$process_button_string .= zen_draw_hidden_field(zen_session_name(),
							zen_session_id());

	return $process_button_string;
    }

    function before_process() {
	global $order, $prekreditor_nor_ot;

	require(DIR_WS_CLASSES . 'kreditor.php');

	$eid = MODULE_PAYMENT_PREKREDITOR_NOR_EID;
	$estoreUser = $_SESSION['customer_id'];
	
	$goodsList = array();
	$n = sizeof($order->products);

	// First all the ordinary items
	for ($i = 0 ; $i < $n ; $i++) {
//	    $price_without_tax = ($order->products[$i]['final_price'] * 100/
//				  (1+$order->products[$i]['tax']/100));
//
	    $price_without_tax = $order->products[$i]['final_price'] *
	    $order->info['currency_value'] * 100;

	    if (MODULE_PAYMENT_PREKREDITOR_NOR_ARTNO == 'id' || MODULE_PAYMENT_PREKREDITOR_NOR_ARTNO == '') {
		$goodsList[] =
		    mk_goods($order->products[$i]['qty'],
			     zen_get_prid($order->products[$i]['id']),
			     $order->products[$i]['name'],
			     $price_without_tax,
			     $order->products[$i]['tax'],
			     0);
	    } else {
		$goodsList[] =
		    mk_goods($order->products[$i]['qty'],
			     $order->products[$i][MODULE_PAYMENT_PREKREDITOR_NOR_ARTNO],
			     $order->products[$i]['name'],
			     $price_without_tax,
			     $order->products[$i]['tax'],
			     0);
	    }
	}
	
	
	// Then the extra charges like discount, invoicefee and shipping.
	foreach($GLOBALS['order_totals'] as $k_global => $v_global)
	{
	
		if(is_int(strpos(strtolower($v_global['code']),'discount')) || is_int(strpos(strtolower($v_global['title']),'discount'))
			|| is_int(strpos(strtolower($v_global['code']),'coupon')) || is_int(strpos(strtolower($v_global['title']),'coupon')))
		{
			$tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PREKREDITOR_NOR_TAX_CLASS);
			$name = strip_tags($v_global['title']);
			$value = -$v_global['value'];
			$tax = $tod_rate*1;
			$name = str_replace(":", "", $name);
			$price_without_tax = $value*$order->info['currency_value']*100;
			if (DISPLAY_PRICE_WITH_TAX == 'true') {
				$price_without_tax = ($price_without_tax/(1+$tax/100));
			}
			if ($value != "" && $value != 0) 
				$goodsList[] = mk_goods(1, "",
							$name,
							$price_without_tax, $tax, 0);
		}
		
		if(is_int(strpos(strtolower($v_global['code']),'charge')) || is_int(strpos(strtolower($v_global['title']),'charge'))
			|| is_int(strpos(strtolower($v_global['code']),'payment')) || is_int(strpos(strtolower($v_global['title']),'payment'))
			|| is_int(strpos(strtolower($v_global['code']),'fee')) || is_int(strpos(strtolower($v_global['title']),'fee')))
		{
			$tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PREKREDITOR_NOR_TAX_CLASS);
			$name = strip_tags($v_global['title']);
			$value = $v_global['value'];
			$tax = $tod_rate*1;                        
			$name = str_replace(":", "", $name);
			$price_without_tax = $value*$order->info['currency_value']*100;
			if (DISPLAY_PRICE_WITH_TAX == 'true') {
				$price_without_tax = ($price_without_tax/(1+$tax/100));
			}
			if ($value != "" && $value != 0) 
				$goodsList[] = mk_goods(1, "",
							$name,
							$price_without_tax, $tax, 0);
		}
	}


	if (zen_not_null($order->info['shipping_method'])) {
	    $price_without_tax = $order->info['shipping_cost'] *
	      $order->info['currency_value']*100;
	    $tod_rate = zen_get_tax_rate(MODULE_PAYMENT_PREKREDITOR_NOR_TAX_CLASS);
	    $tax = $tod_rate*1;

	    if (DISPLAY_PRICE_WITH_TAX == 'true') {
		$price_without_tax = ($price_without_tax/(1+$tax/100));
	    }

	    $goodsList[] = mk_goods(1, "",
				    $order->info['shipping_method'],
				    $price_without_tax, $tax, 0);
	}

	$secret = MODULE_PAYMENT_PREKREDITOR_NOR_SECRET;
	$estoreOrderNo = "";
	$shipmentfee = 0;
	$shipmenttype = 1;

	$handlingfee = 0;
	$ready_date = "";

	// Fixes potential security problem
	$order->delivery['firstname'] = $_POST['predkreditor_fname'];
	$order->billing['firstname'] =  $_POST['predkreditor_fname'];
	$order->delivery['lastname'] =  $_POST['predkreditor_lname'];
	$order->billing['lastname'] =   $_POST['predkreditor_lname'];
	$order->delivery['street_address'] =$_POST['predkreditor_street'];
	$order->billing['street_address'] = $_POST['predkreditor_street'];
	$order->delivery['postcode'] = $_POST['predkreditor_postno'];
	$order->billing['postcode'] = $_POST['predkreditor_postno'];
	$order->delivery['city'] = $_POST['predkreditor_city'];
	$order->billing['city'] = $_POST['predkreditor_city'];
	$order->delivery['telephone'] = $_POST['predkreditor_phone'];
	$order->billing['telephone'] = $_POST['predkreditor_phone'];
	$order->delivery['email_address'] = $_POST['predkreditor_email'];
	$order->billing['email_address'] = $_POST['predkreditor_email'];

	$fname = $_POST['prekreditor_nor_fname'];
	$lname = $_POST['prekreditor_nor_lname'];
	$addr = mk_addr_no("",
			$_POST['prekreditor_nor_street'],
			$_POST['prekreditor_nor_postno'],
			$_POST['prekreditor_nor_city'],
			"",
			$_POST['prekreditor_nor_phone'],
			$_POST['prekreditor_nor_email']);
	$passwd = "";
	$clientIp = $_SERVER["REMOTE_ADDR"];
	$newPasswd = "";

	$pno = "";

	$flags = $KRED_PRE_PAY;

	$status =
	    add_invoice_no($eid, $estoreUser, $secret, $estoreOrderNo,
			$goodsList, $shipmentfee, $shipmenttype,
			$handlingfee, $pno, $fname, $lname, $addr,
			$passwd, $clientIp, $newPasswd, $flags,
			$comment, $ready_date, "", $result);


	if ($status == 0){
	    $order->kreditorref=$result; 
	    $payment['tan']=$result;
	} else {
	    zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT,
				       'payment_error=prekreditor_nor&error=' .
				       urlencode($result),
				       'SSL', true, false));

	}
    }

    function after_process() {
	global $insert_id, $order, $db, $order_total_modules;

	$find_st_optional_field_query =
	    $db->Execute("show columns from " . TABLE_ORDERS);

	$has_kreditor_ref = false;

	while(!$find_st_optional_field_query->EOF) {
	  if ($find_st_optional_field_query->fields['Field'] ==
	      "kreditorref" ) 
	    $has_kreditor_ref = true;
	  $find_st_optional_field_query->MoveNext();
	}

// 	while($fields = zen_db_fetch_array($find_st_optional_field_query)){
// 	    if ( $fields['Field'] == "kreditorref" ) 
// 		$has_kreditor_ref = true;
// 	}
	
	if ($has_kreditor_ref)
	    $db->Execute("update " . TABLE_ORDERS . " set kreditorref='" .
			 $order->kreditorref . "' " . " where orders_id = '" .
			 $insert_id . "'");

      
	// Insert transaction # into history file
	$sql_data_array = array('orders_id' => $insert_id, 
				'orders_status_id' => (
				    $order->info['order_status']), 
				'date_added' => 'now()', 
				'customer_notified' => 0,
				'comments' => ('Prepay accepted by Klarna ' .
					       date("Y-m-d G:i:s") .
					       ' Invoice #: ' .
					       $order->kreditorref));

	zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);

	$secret = MODULE_PAYMENT_PREKREDITOR_NOR_SECRET;
	$eid = MODULE_PAYMENT_PREKREDITOR_NOR_EID;
	$invno = $order->kreditorref;

	update_orderno($eid, $invno, $secret, $insert_id, $result);

        $_SESSION['cart']->reset(true);

	// unregister session variables used during checkout
	unset($_SESSION['sendto']);
	unset($_SESSION['billto']);
	unset($_SESSION['shipping']);
	unset($_SESSION['payment']);
	unset($_SESSION['comments']);
	$order_total_modules->clear_posts();//ICW ADDED FOR CREDIT CLASS SYSTEM

	zen_redirect("https://www.kreditor.se/show_pre_invoice.yaws?invno=$result&text=".urlencode(MODULE_PAYMENT_PREKREDITOR_NOR_PRETEXT)."&return=".base64_encode(zen_href_link(FILENAME_CHECKOUT_SUCCESS, '', 'SSL')));

	return false;

    }

    function get_error() {
	
	if (isset($_GET['error']) &&
	    strlen($_GET['error']) > 0) {
	    $error = stripslashes(urldecode($_GET['error']));
	} else {
	    $error = MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_ERROR_MESSAGE;
	}

	return array('title' => MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_ERROR,
		     'error' => $error);
    }

    function check() {
	global $db;

	if (!isset($this->_check)) {
	    $check_query = $db->Execute("select configuration_value from " .
					TABLE_CONFIGURATION .
					" where configuration_key = " .
					"'MODULE_PAYMENT_PREKREDITOR_NOR_STATUS'");
            $this->_check = $check_query->RecordCount();
	}
	return $this->_check;
    }

    function install() {
        global $db;
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Enable Norwegian Klarna Module', 'MODULE_PAYMENT_PREKREDITOR_NOR_STATUS', 'True', 'Do you want to accept Norwegian Klarna pre-payments?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");

	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Payment Zone', 'MODULE_PAYMENT_PREKREDITOR_NOR_ZONE', '0', 'If a zone is selected, only enable this payment method for that zone.', '6', '2', 'zen_get_zone_class_title', 'zen_cfg_pull_down_zone_classes(', now())");
      
 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Merchant ID', 'MODULE_PAYMENT_PREKREDITOR_NOR_EID', '0', 'Merchant ID (estore id) to use for the Klarna service (provided by Klarna)', '6', '0', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Shared secret', 'MODULE_PAYMENT_PREKREDITOR_NOR_SECRET', '', 'Shared secret to use with the Klarna service (provided by Klarna)', '6', '0', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Text on invoice page', 'MODULE_PAYMENT_PREKREDITOR_NOR_PRETEXT', '".KREDITOR_LANG_INFO_NO_PAYINVOICE.".', 'Text above invoice on web page.', '6', '0', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Product artno attribute (id or model)', 'MODULE_PAYMENT_PREKREDITOR_NOR_ARTNO', 'id', 'Product attribute to use for artno', '6', '0', 'zen_cfg_select_option(array(\'id\', \'model\'), ', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Pre-populate personnummer field', 'MODULE_PAYMENT_PREKREDITOR_NOR_PRE_POPULATE', 'False', 'Do you want to pre-populate the personnummer field?', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");

	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Ignore table', 'MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_TOTAL_IGNORE', 'ot_tax,ot_total,ot_subtotal,ot_shipping', 'Ignore these entries from order total list when compiling the invoice data', '6', '2', now())");

	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort order of display.', 'MODULE_PAYMENT_PREKREDITOR_NOR_SORT_ORDER', '44', 'Sort order of display. Lowest is displayed first.', '6', '0', now())");
      
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Extra info', 'MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_TITLE_CUST', '', 'Extra info, eg &lt;strong>OBS!&lt;/strong> invoice charge will be added 25:-', '6', '0', now())");

 	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Terms of payment', 'MODULE_PAYMENT_PREKREDITOR_NOR_TERMS', '".KREDITOR_LANG_INFO_NO_PAYMENT."', '', '6', '0', now())");

	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, use_function, set_function, date_added) values ('Tax Class', 'MODULE_PAYMENT_PREKREDITOR_NOR_TAX_CLASS', '0', 'Use the following tax class on the payment charge.', '6', '6', 'zen_get_tax_class_title', 'zen_cfg_pull_down_tax_classes(', now())");

    }

    function remove() {
	global $db;
	$db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    }

    function keys() {
	return array('MODULE_PAYMENT_PREKREDITOR_NOR_STATUS',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_STATUS_ID',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_EID',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_SECRET',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_PRETEXT',
	         'MODULE_PAYMENT_PREKREDITOR_NOR_ARTNO',
	         'MODULE_PAYMENT_PREKREDITOR_NOR_PRE_POPULATE',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_ORDER_TOTAL_IGNORE',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_ZONE',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_TERMS',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_TAX_CLASS',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_TEXT_TITLE_CUST',
		     'MODULE_PAYMENT_PREKREDITOR_NOR_SORT_ORDER');
    }
}
?>
